package com.igeek.boot_4_druid.controller;

import com.igeek.boot_4_druid.entity.User;
import com.igeek.boot_4_druid.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Author: zhiyu
 * @Date:19:54
 * @DESC:
 */
@RestController
public class UserController {
    @Autowired
    UserService userService;
    @DeleteMapping("/deleteById")
    public boolean deleteByPrimaryKey(Integer id){
        return userService.deleteByPrimaryKey(id);
    };
    @PostMapping("/addUser")
    public boolean insert(@RequestBody User user){
        return userService.insert(user);
    };
    @GetMapping("findByName")
    public List<User> selectAll(String name){
        return userService.selectAll(name);
    };
    @PutMapping("/updateUser")
    public boolean updateByPrimaryKey(MultipartFile file, @RequestParam("id") Integer id){
        String upload = upload(file);
        System.out.println(upload);
        User user = new User();
        user.setId(id);
        user.setPic(upload);
        if (upload!=null){
            return userService.updateByPrimaryKey(user);
        }
        else {
            return false;
        }
    };
    public String upload(MultipartFile multipartFile){
        String originalFilename = multipartFile.getOriginalFilename();
        String type=originalFilename.substring(originalFilename.indexOf("."));
        UUID uuid = UUID.randomUUID();
        File file = new File("D:\\workspace\\idea\\JKY\\testSpringBoot\\boot_4_druid\\src\\main\\resources\\pic\\",uuid+type);
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "/pic/"+uuid+type;
    }
}
